package com.wangyadong.hobby.schedule.jobtask.classload.chapter3;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/10/3010:19
 **/
public class MyclassLoad extends ClassLoader {

    private final static String DEFAULT_DIR = "D:\\git\\hobby\\remote-wangyadong-hobby\\hobby\\src\\test\\java\\com\\wangyadong\\hobby\\schedule\\jobtask\\classload\\chapter3";
    private String dir = DEFAULT_DIR;
    private String classLoaderName;

    public MyclassLoad() {
        super();
    }

    public MyclassLoad(String classLoaderName) {
        super();
        this.classLoaderName = classLoaderName;
    }

    public MyclassLoad(String classLoaderName, ClassLoader parent) {
        super(parent);
        this.classLoaderName = classLoaderName;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String classPath = name.replace(".", "/");
        File classFile = new File(classPath);
        if (!classFile.exists()) {
            throw new ClassNotFoundException("");
        }
        byte[] bytes = loadClassByte(classFile);
        if (bytes == null || bytes.length == 0) {
            throw new ClassNotFoundException("");
        }
        return this.defineClass(name, bytes, 0, bytes.length);
    }

    public byte[] loadClassByte(File classFile) {

        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             FileInputStream fis = new FileInputStream(classFile)
        ) {
            byte[] bytes = new byte[1024];
            int len;
            while ((len = fis.read(bytes)) != -1) {
                baos.write(bytes, 0, len);
            }
            baos.flush();
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }


    }

    public String getDir() {
        return dir;
    }

    public void setDir(String dir) {
        this.dir = dir;
    }

    public String getClassLoaderName() {
        return classLoaderName;
    }

    public void setClassLoaderName(String classLoaderName) {
        this.classLoaderName = classLoaderName;
    }
}
